package com.zros.modules.system.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zros.common.constant.Constant;
import com.zros.common.exception.JeecgBootException;
import com.zros.modules.system.dto.CreateUser;
import com.zros.modules.system.dto.QueryUser;
import com.zros.modules.system.dto.UpdateUser;
import com.zros.modules.system.dto.UserInfo;
import com.zros.modules.system.entity.DataResource;
import com.zros.modules.system.entity.Organization;
import com.zros.modules.system.entity.OrganizationUser;
import com.zros.modules.system.entity.Role;
import com.zros.modules.system.entity.User;
import com.zros.modules.system.entity.UserRole;
import com.zros.modules.system.mapper.UserMapper;
import com.zros.modules.system.service.IDataResourceService;
import com.zros.modules.system.service.IOrganizationService;
import com.zros.modules.system.service.IOrganizationUserService;
import com.zros.modules.system.service.IRoleService;
import com.zros.modules.system.service.IUserRoleService;
import com.zros.modules.system.service.IUserService;

/**
 * @ClassName: UserServiceImpl
 * @Description: 用户相关操作接口实现类
 * 
 * @date 2018年5月18日 下午3:20:30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

	@Autowired
	UserMapper userMapper;

	@Autowired
	private IUserRoleService userRoleService;
	
	@Autowired
	private IRoleService roleService;

	@Autowired
	private IOrganizationUserService organizationUserService;
	
	@Autowired
	private IOrganizationService organizationService;
	
	
	@Autowired
	private IDataResourceService dataResourceService;

	/* @Value("${system.defaultPwd}") */
	private String defaultPwd = "123456";

	/* @Value("${system.defaultRoleId}") */
	private Long defaultRoleId;

	@Override
	public Page<UserInfo> selectUserList(Page<UserInfo> page, QueryUser user) {
		Page<UserInfo> pageUserInfo = userMapper.selectUserList(page, user);
		
		//把用户集合取出来
		List<UserInfo> userList = new ArrayList<UserInfo>();
		userList = pageUserInfo.getRecords();
		if(!CollectionUtils.isEmpty(userList)) {
			//把所有的角色转换成map
			Map<Long,String> roleNameMap = new HashMap<Long,String>();
			roleNameMap = roleService.list().stream().collect(Collectors.toMap(Role::getId,Role::getRoleName, (key1, key2) -> key2));
			
			//把所有的校区转换成map
			Map<Long,String> orgNameMap = new HashMap<Long,String>();
			orgNameMap = organizationService.list().stream().collect(Collectors.toMap(Organization::getId,Organization::getOrganizationName, (key1, key2) -> key2));
			
			
			
			//循环用户集合，设置角色名称，机构名称
			for (UserInfo userInfo : userList) {
				try {
					List<String> roleIdList = new ArrayList<String>();
					List<String> orgIdList = new ArrayList<String>();
					List<String> roleNameList = new ArrayList<String>();
					List<String> orgNameList = new ArrayList<String>();
					roleIdList = userInfo.getRoleIdList();
					if (!CollectionUtils.isEmpty(roleIdList)) {
						for (String roleId : roleIdList) {
							roleNameList.add(roleNameMap.get(Long.parseLong(roleId)));
						}
						if (!CollectionUtils.isEmpty(roleNameList)) {
							StringBuffer roleNames = new StringBuffer();
							for (Iterator<String> iterator = roleNameList.iterator(); iterator.hasNext();) {
								String string = (String) iterator.next();
								roleNames.append(string);
								if (iterator.hasNext()) {
									roleNames.append(",");
								}
							}
							userInfo.setRoleName(roleNames.toString());
						}
					}
					orgIdList = userInfo.getOrgIdList();
					if (!CollectionUtils.isEmpty(orgIdList)) {
						for (String orgId : orgIdList) {
							orgNameList.add(orgNameMap.get(Long.parseLong(orgId)));
						}
						if (!CollectionUtils.isEmpty(orgNameList)) {
							StringBuffer orgNames = new StringBuffer();
							for (Iterator<String> iterator = orgNameList.iterator(); iterator.hasNext();) {
								String string = (String) iterator.next();
								orgNames.append(string);
								if (iterator.hasNext()) {
									orgNames.append(",");
								}
							}
							userInfo.setOrgName(orgNames.toString());
						}
					} 
				} finally {
					
				}
			}
		}
		
		
		
		
		return pageUserInfo;
	}

	public static void main(String[] args) {
		String cryptPwd = BCrypt.hashpw("1234567", BCrypt.gensalt());
		System.out.println(cryptPwd);
	}

	@Override
	public boolean createUser(CreateUser user) {
		user.setUserAccount(user.getUserMobile());
		QueryWrapper<User> ew = new QueryWrapper<>();
		ew.and(e -> e.eq("user_mobile", user.getUserMobile()));
		List<User> userList = this.list(ew);
		if (!CollectionUtils.isEmpty(userList)) {
			throw new JeecgBootException("手机号已经存在");
		}
		/*
		 * Long roleId = user.getRoleId(); if (null == roleId) { // 默认值，改成配置 roleId =
		 * defaultRoleId; }
		 */
		/*
		 * List<String> areas = user.getAreas(); if (!CollectionUtils.isEmpty(areas)) {
		 * user.setProvince(areas.get(Constant.Address.PROVINCE));
		 * user.setCity(areas.get(Constant.Address.CITY));
		 * //user.setArea(areas.get(Constant.Address.AREA)); }
		 */
		User userEntity = new User();
		BeanCopier.create(CreateUser.class, User.class, false).copy(user, userEntity, null);
		String pwd = userEntity.getUserPassword();
		if (StringUtils.isEmpty(pwd)) {
			// 默认密码，配置文件配置
			pwd = defaultPwd;
			// 初次登录需要修改密码
			userEntity.setUserStatus("2");
		}
		String cryptPwd = BCrypt.hashpw(pwd, BCrypt.gensalt());
		// userEntity.setArea("110001");
		userEntity.setUserPassword(cryptPwd);
		userEntity.setUserAccount(userEntity.getUserMobile());
		boolean result = this.save(userEntity);
		if (result) {
			user.setId(userEntity.getId());
			user.setUserPassword(cryptPwd);
			List<Long> roleIds = user.getRoleIdList();
			List<UserRole> userRoleList = new ArrayList<UserRole>();
			if (roleIds != null && roleIds.size() > 0) {
				for (Long roleId : roleIds) {
					UserRole userRole = new UserRole();
					userRole.setUserId(userEntity.getId());
					userRole.setRoleId(roleId);
					userRoleList.add(userRole);
				}
			}
			result = userRoleService.saveBatch(userRoleList);

			// 插入机构list
			List<Long> orgIds = user.getOrgIdList();
			List<OrganizationUser> userOrgList = new ArrayList<OrganizationUser>();
			if (orgIds != null && orgIds.size() > 0) {
				for (Long roleId : orgIds) {
					OrganizationUser userRole = new OrganizationUser();
					userRole.setUserId(userEntity.getId());
					userRole.setOrganizationId(roleId);
					userOrgList.add(userRole);
				}
			}
			result = organizationUserService.saveBatch(userOrgList);
		}
		return result;
	}

	@Override
	@CacheEvict(value = "users", key = "'id_'.concat(#user.id)")
	public boolean updateUser(UpdateUser user) {
		QueryWrapper<User> ew = new QueryWrapper<>();
		ew.ne("id", user.getId())
				.and(e -> e.eq("user_mobile", user.getUserMobile()));
		List<User> userList = this.list(ew);
		if (!CollectionUtils.isEmpty(userList)) {
			throw new JeecgBootException("手机号已经存在");
		}
		List<String> areas = user.getAreas();
		if (!CollectionUtils.isEmpty(areas)) {
			user.setProvince(areas.get(Constant.Address.PROVINCE));
			user.setCity(areas.get(Constant.Address.CITY));
			user.setArea(areas.get(Constant.Address.AREA));
		}
		User userEntity = new User();
		BeanCopier.create(UpdateUser.class, User.class, false).copy(user, userEntity, null);
		
		/*String pwd = userEntity.getUserPassword();
		if (!StringUtils.isEmpty(pwd)) {
			String cryptPwd = BCrypt.hashpw(pwd, BCrypt.gensalt());
			userEntity.setUserPassword(cryptPwd);
		}*/
		
		QueryWrapper<User> wrapper = new QueryWrapper<>();
		wrapper.eq("id", userEntity.getId());
		userEntity.setUserAccount(userEntity.getUserMobile());
		boolean result = this.update(userEntity, wrapper);
		if (result) {

			//删除原有的角色信息
			QueryWrapper<UserRole> wpd = new QueryWrapper<>();
			wpd.eq("user_id", userEntity.getId());
			userRoleService.remove(wpd);
			
			//新增角色信息
			List<Long> roleIds = user.getRoleIdList();
			List<UserRole> userRoleList = new ArrayList<UserRole>();
			if (roleIds != null && roleIds.size() > 0) {
				for (Long roleId : roleIds) {
					UserRole userRole = new UserRole();
					userRole.setUserId(userEntity.getId());
					userRole.setRoleId(roleId);
					userRoleList.add(userRole);
				}
			}
			result = userRoleService.saveBatch(userRoleList);
			
			//删除原有的机构信息
			QueryWrapper<OrganizationUser> wpd2 = new QueryWrapper<OrganizationUser>();
			wpd2.eq("user_id", userEntity.getId());
			//userRoleService.remove(wpd);
			organizationUserService.remove(wpd2);
			
			List<Long> orgIds = user.getOrgIdList();
			List<OrganizationUser> userOrgList = new ArrayList<OrganizationUser>();
			if (orgIds != null && orgIds.size() > 0) {
				for (Long roleId : orgIds) {
					OrganizationUser userRole = new OrganizationUser();
					userRole.setUserId(userEntity.getId());
					userRole.setOrganizationId(roleId);
					userOrgList.add(userRole);
				}
			}
			result = organizationUserService.saveBatch(userOrgList);
//            List<Long> roleIds = user.getRoleIdList();
//            List<UserRole> userRoleList = new ArrayList<UserRole>();
//            if(roleIds!=null && roleIds.size()>0)
//            {
//            	for (Long roleId : roleIds) 
//            	{
//            		UserRole userRole = new UserRole();
//                    userRole.setUserId(userEntity.getId());
//                    userRole.setRoleId(roleId);
//                    userRoleList.add(userRole);
//				}
//            }
//            result = userRoleService.saveBatch(userRoleList);
//            
//            //插入机构list
//            List<Long> orgIds = user.getOrgIdList();
//            List<OrganizationUser> userOrgList = new ArrayList<OrganizationUser>();
//            if(orgIds!=null && orgIds.size()>0)
//            {
//            	for (Long roleId : orgIds) 
//            	{
//            		OrganizationUser userRole = new OrganizationUser();
//                    userRole.setUserId(userEntity.getId());
//                    userRole.setOrganizationId(roleId);
//                    userOrgList.add(userRole);
//				}
//            }
//            result = organizationUserService.saveBatch(userOrgList);

		}
		return result;
	}

	@Override
	@CacheEvict(value = "users", key = "'id_'.concat(#userId)")
	public boolean deleteUser(Long userId) {
		boolean result = this.removeById(userId);
		if (result) {
			QueryWrapper<UserRole> wpd = new QueryWrapper<>();
			wpd.eq("user_id", userId);
			userRoleService.remove(wpd);
		}
		return result;
	}

	@Override
	@Cacheable(value = "users", key = "'account_'.concat(#userAccount)")
	public User queryUserByAccount(String userAccount) {
		QueryWrapper<User> ew = new QueryWrapper<>();
		ew.and(e -> e.eq("user_account", userAccount).or().eq("user_email", userAccount).or().eq("user_mobile",
				userAccount));
		return this.getOne(ew);
	}
	
	@Override
	public UserInfo queryUserInfoByAccount(String userAccount,String dataResourceMethod) {
		UserInfo userInfo = new UserInfo();
		
		QueryWrapper<User> ew = new QueryWrapper<>();
		ew.and(e -> e.eq("user_account", userAccount).or().eq("user_email", userAccount).or().eq("user_mobile",
				userAccount));
		User user = this.getOne(ew);
		BeanCopier.create(User.class, UserInfo.class, false).copy(user, userInfo, null);
		
		
		Long userId = user.getId();
		userInfo.setId(String.valueOf(userId));
		//角色信息
		List<Role> userRole = userRoleService.queryRolesByUserId(userId);
		if (!CollectionUtils.isEmpty(userRole)) {
			List<String> roles = new ArrayList<String>();
			for (Role role : userRole) {
				roles.add(role.getRoleKey());
			}
			userInfo.setRoles(roles);
		}
		//机构信息
		List<Organization> userOrg = organizationUserService.queryOrgsByUserId(userId);
		if (!CollectionUtils.isEmpty(userOrg)) {
			List<String> orgs = new ArrayList<String>();
			for (Organization role : userOrg) {
				orgs.add(role.getId().toString());
			}
			userInfo.setOrgIdList(orgs);
		}
		//数据权限信息
		List<DataResource> userDataRes = dataResourceService.queryDataResourceByUserId(userId,dataResourceMethod);
		if (!CollectionUtils.isEmpty(userDataRes)) {
			List<Integer>  dataResourceKey = new ArrayList<Integer>();
			for (DataResource role : userDataRes) 
			{
				dataResourceKey.add(Integer.parseInt(role.getDataResourceKey()));
			}
			userInfo.setDataResourceKey(Collections.max(dataResourceKey).toString());
		}
		return userInfo;
	}
	
	
	
	
	
	
}
